package com.maple.soa.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常捕获，优先级仅次于直接使用@ExceptionHandler
 * 灵活、方便维护推荐使用
 * @author lijian
 * @date 2020/7/20
 */
@ControllerAdvice
@Slf4j
public class GlobalException implements HandlerExceptionResolver {
    /**
     * 上传文件大小超过最大值
     * @param e
     * @return
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ModelAndView MaxUploadException(MaxUploadSizeExceededException e) {
        log.error("upload file big max size!", e);

        ModelMap modelMap = new ModelMap();
        modelMap.addAttribute("msg", "文件最大为20M");

        return new ModelAndView("upload/error", modelMap);
    }

    /**
     * 其他未知异常捕获，自定义异常捕获，优先级最低
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelMap modelMap = new ModelMap();
        log.error("upload file big max size!", ex);

        if (ex instanceof MaxUploadSizeExceededException) {
            modelMap.addAttribute("msg", "文件最大为20M!!!");
        } else {
            modelMap.addAttribute("msg", "其他未知异常");
        }

        return new ModelAndView("upload/error", modelMap);
    }
}
